package com.glq1218.background.controller;

import com.glq1218.common.config.CosConfig;
import com.glq1218.common.handler.MyWebSocketHandler;
import com.glq1218.common.model.Result;
import com.glq1218.common.util.CosUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author glq1218
 */
@RestController
@RequestMapping("/system")
@Tag(name = "系统信息接口", description = "获取系统信息")
@RequiredArgsConstructor
public class SystemController {
    private final CosConfig cosConfig;

    @Operation(summary = "获取后台在线人数", description = "获取后台在线人数")
    @GetMapping("/getBackgroundOnline")
    public Result<?> getBackgroundOnline() {
        return Result.ok(MyWebSocketHandler.getOnlineCount());
    }

    @Operation(summary = "获取前台在线人数", description = "获取前台在线人数")
    @GetMapping("/getForegroundOnline")
    public Result<?> getForegroundOnline() throws IOException {
        URL uri = new URL("http://localhost:8082/getOnline");
        HttpURLConnection connection = (HttpURLConnection) uri.openConnection();
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        } catch (IOException e) {
            throw new RuntimeException("访问前台服务失败");
        }
        String message = bufferedReader.readLine();
        bufferedReader.close();
        return Result.ok(Integer.parseInt(message));
    }

    @PostMapping("/upload")
    @Tag(name = "上传文件")
    public Result<?> upload(@RequestParam("file") MultipartFile file) {
        return Result.ok("上传成功", CosUtils.uploadFile(cosConfig, file));
    }
}
